package cn.bearspark.user.provider.dao.buffer;

import cn.bearspark.framework.redis.starter.buffer.list.RedisBaseListBuffer;
import cn.bearspark.user.provider.dao.key.UserBufferKeyBuilder;
import cn.bearspark.user.provider.dao.mapper.UserFollowMapper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 用户关注者 id 列表的缓存器
 *
 * @author f
 */
@Component
public class FollowerIdListBuffer extends RedisBaseListBuffer<Long> {

    /**
     * 设置关注者的最多数量，默认是 1000
     * <p>
     * 一般不会有人的关注量在 1000 以上，所以这个限制一般不会起作用
     */
    private static final int MAX_FOLLOWER_NUM = 1000;

    private final UserFollowMapper userFollowMapper;

    private final UserBufferKeyBuilder userBufferKeyBuilder;

    public FollowerIdListBuffer(RedisTemplate<String, Object> redisTemplate,
                                UserFollowMapper userFollowMapper,
                                UserBufferKeyBuilder userBufferKeyBuilder) {
        super(redisTemplate);
        this.userFollowMapper = userFollowMapper;
        this.userBufferKeyBuilder = userBufferKeyBuilder;
    }

    /**
     * 获取指定用户所有关注者的用户 id
     *
     * @param userId 指定的用户 id
     * @return 指定用户所有关注者的用户 id 集合
     */
    public List<Long> listFollowerId(long userId) {
        return super.range(
                userBufferKeyBuilder.buildFollowersIdKey(userId),
                0, MAX_FOLLOWER_NUM,
                () -> userFollowMapper.listFollowersId(userId, MAX_FOLLOWER_NUM)
        );
    }
}
